package com.example.dao;

import com.example.task01_model.User;
import com.example.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UserDao {

    public int createUser(User user) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //1.获取连接
            connection = DBUtil.getConnection();
            //2.准备SQL语句
            String sql = "insert into t_user values(null,?,?)";
            //3.获取预处理对象
            ps = connection.prepareStatement(sql);
            //4.设置占位符
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            //5.执行SQL语句
            int i = ps.executeUpdate();
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //6.关闭资源
            try {
                DBUtil.closeConnection(connection, ps);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0; //执行失败
    }
}
